import { Button, Card, Table, Modal, Form, Input, message } from "antd";
import { useEffect, useState } from "react";
import type { ColumnsType } from 'antd/es/table';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons'
import { getTrademarkInfo, reMoveTd, reqAddTd, reqUpDateTd } from "@/api/trademark";
import type {  tdItem } from "@/api/trademark/model/trademarkType";
import FormItem from "antd/lib/form/FormItem";
import Upload, { RcFile, UploadProps } from "antd/lib/upload";
import { UploadChangeParam, UploadFile } from "antd/lib/upload/interface";





// 定义表格数据类型
export default function HospitalSet() {

  // 定义动态数据
  const [page, setPage] = useState(1)
  const [limit, setLimit] = useState(3)
  const [total,setTotal] = useState(3)
  const [tdList, setTdList] = useState<tdItem[]>([])
  const [noSave,setNoSave] = useState(true)
  const [itemState,setItemState] = useState(true)
  interface DataType {
    key: number,
    tdName: string,
    logoUrl: string,

  }

  // 定义表格每列表头
  const columns: ColumnsType<DataType> = [
    {
      title: '序号',
      dataIndex: 'num',
      render: (text, record, index) => {
        return <span>{index + 1}</span>
      },
    },
    {
      title: '品牌名称',
      dataIndex: 'tdName'
    },
    {
      title: '品牌logo',
      dataIndex: 'logoUrl',
      render:(text,record) => {
        return <img width='100px' src={text} alt={record.tdName}></img>
      }
    },
    {
      title: '操作',
      dataIndex: 'action',
      render:(text,record) => {
        return <>
        <Button 
        style={{backgroundColor:'orange',color:'white',marginRight:'20px'}}
        onClick={() => addOrUpdate(record)}
        >修改</Button>
        <Button type="primary" danger onClick={() => delTd(record)}>删除</Button>
        </>
      }
    }
  ]

  // 定义表格数据
  let dataList: DataType[] = []
  tdList.forEach(item => {
    dataList.push({
      key:item.id as number,
      tdName:item.tmName,
      logoUrl:item.logoUrl
    })
  })


  // 定义请求获取trademark信息函数
  const getTd = async (page:number,limit:number) => {
    try {
      const result = await getTrademarkInfo(page, limit)
      setTdList(result.records)
      setTotal(result.total)
      setPage(result.current)
      setLimit(result.size)
      
    } catch (error) {
      console.log(error)
    }
  }

  // 组件刚创建好时发送请求
  useEffect(() => {
    getTd(page,limit)
  },[])


  const [form] = Form.useForm();
  // 点击添加或者修改时的函数
  const addOrUpdate = (currentObj:DataType | undefined) => {

    if(currentObj){
      setCurrentId(currentObj.key)
      setImageUrl(currentObj.logoUrl)
      setCurrentName(currentObj.tdName)
      form.setFieldsValue({
        nowName:currentObj.tdName
      })
    }else{
      // 设置表单里面的数据和自定义的动态数据
      setImageUrl('');
      setCurrentName('')
      form.resetFields()
      form.setFieldsValue({
        nowName:''
      })
      
    }
    setIsModalOpen(true)
  }

  // 点击删除按钮时的函数
  const delTd = async (record:DataType) => {
    try {
      await reMoveTd(record.key as number)
      message.success(`删除${record.tdName}成功`)
      if(tdList.length > 1){

        getTd(page,limit)
      }else{
        getTd(page - 1, limit)
      }
    } catch (error) {
      message.error(`删除${record.tdName}失败`)
      
    }
  }

  //对话框相关的函数信息****************************
  const [isModalOpen, setIsModalOpen] = useState(false);

  const showModal = () => {
    setIsModalOpen(true);
  };

  // 对话框点击确定函数
  const handleOk = async () => {
    
    if(typeof currentId === 'string'){
      // 没有id新增
      try {
        await reqAddTd({id:currentId,tmName:currentName as string,logoUrl:imageUrl as string})
        message.success('保存成功')
        setIsModalOpen(false);
        getTd(page,limit)
        
      } catch (error) {
        message.error('保存失败')
        
      }
    }else{
      // 有id修改
      try {
        await reqUpDateTd({id:currentId,tmName:currentName as string,logoUrl:imageUrl as string})
        message.success('修改成功')
        setIsModalOpen(false);
        getTd(page,limit)
      } catch (error) {
        message.error('修改失败')
        
      }

    }
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  }; 

  const onFinish = (values: any) => {
    console.log('Success:', values);
  };

  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
  };

  //对话框相关的函数信息****************************


  // 图片上传相关函数信息**************************************

  
  const beforeUpload = (file: RcFile) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('You can only upload JPG/PNG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('Image must smaller than 2MB!');
    }
    if(isJpgOrPng && isLt2M) setNoSave(false)
    return isJpgOrPng && isLt2M;
  };


  const [loading, setLoading] = useState(false);
  const [currentId,setCurrentId] = useState<number | string>('')
  const [imageUrl, setImageUrl] = useState<string>();
  const [currentName,setCurrentName] = useState<string>()


  const handleChange: UploadProps['onChange'] = (info: UploadChangeParam<UploadFile>) => {
    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      setLoading(false);
      // setImageUrl(url);
      setImageUrl(info.file.response.data)
    }
  };

  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>Upload</div>
    </div>
  );

  const changeName = (changedValues: any ) => {
    setCurrentName(changedValues.nowName)
  }


  // 图片上传相关函数信息**************************************


  return (

    <Card
      title={<Button 
              type="primary" 
              icon={<PlusOutlined />}
              onClick={() => addOrUpdate(undefined)}
              >
              添加
              </Button>}

      style={{ margin: '0 20px' }}>
      <Table
        columns={columns}
        dataSource={dataList}
        pagination={{
          showSizeChanger:true,
          current: page,
          total: total,
          pageSize: limit,
          pageSizeOptions:[3,5,7],
          defaultCurrent: 1,
          defaultPageSize: 3,
          onChange(page,pageSize){
            // 这里如果是直接修改page，和limit的值，
            // 然后通过生命周期的变化来发送请求的话，浏览器会报数据长度比total短，但是比pagesize长的错误
            getTd(page,pageSize)
          }
        }}
      >

      </Table>


      {/* 添加或修改时的对话框 */}
      <Modal title="添加品牌" visible={isModalOpen}  
      onOk={handleOk}  
      okButtonProps={{disabled:noSave || itemState}}
      onCancel={handleCancel}>
        <Form
         form={form}
         preserve={true}
         labelCol={{ span: 4 }}
         wrapperCol={{ span: 12 }}
         onFinish={onFinish}
         onFinishFailed={onFinishFailed}
         onValuesChange={changeName}
         >
            <Form.Item
            label="品牌名称"
            name="nowName"
            style={{paddingBottom:'20px'}}
            rules={[
              {validator:(rule,value,callback) => {
                return new Promise((resolve,reject) => {
                  let rules = /^[a-zA-Z0-9_\u4e00-\u9fa5]+$/
                  let result = rules.test(value)
                  if(result){
                    setItemState(false)
                    return resolve('ok')
                  }else{
                    setItemState(true)

                    return reject('不符合命名规则')
                  }
                })
              }}
            ]}
          >
            <Input />
          </Form.Item>

          {/* 图片上传 */}
          <FormItem 
          label="品牌LOGO"
          rules={[
          
          ]}
          >
              <Upload
              listType="picture-card"
              className="avatar-uploader"
              showUploadList={false}
              action="http://gmall-h5-api.atguigu.cn/admin/product/upload"
              beforeUpload={beforeUpload}
              onChange={handleChange}
            >
              {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
            </Upload>

          </FormItem>
        </Form>
      </Modal>

    </Card>

  );
}
